﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace CourseManagerment.Common
{
    public class PasswordHelper
    {
        //注册指定的属性类型、所有者类型、属性元数据和值验证回调的 附加属性 属性。
        public static readonly DependencyProperty PasswordProperty =
            DependencyProperty.RegisterAttached("Password", typeof(string), typeof(PasswordHelper),
                new FrameworkPropertyMetadata("", new PropertyChangedCallback(OnPropertyChanged)));

        //更新状态
        static bool _isUpdating = false;

        public static string GetPassword(DependencyObject d)
        {
            return d.GetValue(PasswordProperty).ToString();
        }
        public static void SetPassword(DependencyObject d, string value)
        {
            d.SetValue(PasswordProperty, value);
        }

        //依赖属性PasswordProperty变化触发的事件 更改UI的属性值
        private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            PasswordBox password = d as PasswordBox;
            password.PasswordChanged -= Password_PasswordChanged;
            //如果前台没有更新的时候
            if (!_isUpdating)
                password.Password = e.NewValue?.ToString();//依赖属性变化，将值推送给d
            password.PasswordChanged += Password_PasswordChanged;
        }
        #region 当UI密码框的内容变化触发的依赖属性

        //注册指定的属性类型、所有者类型、属性元数据和值验证回调的 附加属性 属性。
        public static readonly DependencyProperty AttachProperty =
            DependencyProperty.RegisterAttached("Attach", typeof(bool), typeof(PasswordHelper),
                new FrameworkPropertyMetadata(default(bool), new PropertyChangedCallback(OnAttached)));

        public static bool GetAttach(DependencyObject d)
        {
            return (bool)d.GetValue(AttachProperty);
        }
        public static void SetAttach(DependencyObject d, bool value)
        {
            d.SetValue(AttachProperty, value);
        }

        //AttachProperty变化触发的事件，依赖属性第一次变化，绑定一个事件，
        private static void OnAttached(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            PasswordBox password = d as PasswordBox;
            password.PasswordChanged += Password_PasswordChanged;//密码框内容变化事件
        }

        //挂接d的事件（密码框的内容变化事件）
        private static void Password_PasswordChanged(object sender, RoutedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
            _isUpdating = true;//更新前
            SetPassword(passwordBox, passwordBox.Password);//设置依赖属性PasswordProperty的值
            _isUpdating = false;//更新后
        }
        #endregion 



    }
}
